import React from 'react';
import {Dimensions, Platform, Text, TouchableWithoutFeedback, View, ActivityIndicator} from 'react-native';
import PropTypes from 'prop-types';
import AutoHeightWebView from 'react-native-autoheight-webview';
import StringUtil from "../utils/StringUtil";
import ImageHorizontalSelectView from "./ImageHorizontalSelectView";
/**
 * 用来展示html的view
 * @param props
 * @returns {*}
 * @constructor
 */

class HTMLDisplayView extends React.Component {

    constructor(props) {
        super(props);
        this.state = {height: 0, hardware:false};
    }

    componentDidMount(){
        setTimeout(()=>{
            this.setState({hardware: true});
        }, 500);
    }

    componentWillUnmount(){
        this.setState({hardware: false});
    }

    render() {
        const props = this.props;
        if (Platform.OS === 'android' && Platform.Version >= 21 && Platform.Version < 23) {
            const images = StringUtil.imagesFromHTML(props.html);
            const text = StringUtil.removeHTMLTag(props.html);
            return <View style={{alignItems: 'stretch', flexGrow: 1, ...props.containerStyle}}>
                <Text style={{
                    fontSize: 15,
                    fontWeight: '400',
                    color: '#333',
                    marginHorizontal: 15,
                    lineHeight: 25, ...props.textStyle,
                }}>{text}</Text>
                <ImageHorizontalSelectView containerStyle={{marginTop: 15}} images={images} editable={false}
                                           hideWhenNoImage={true}
                                           height={WIN_WIDTH / 2}
                />
            </View>;
        } else {
            const html = this.props.html ?( this.props.autoResizingImage ? this.props.html.replace(/<img[^>]*>/gi, function (match, capture) {
                return match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, '').replace('<img ', '<img style="max-width:100%;height:auto;" '); // 替换style
            }) : this.props.html): null;
            return this.state.hardware ? <View style={{alignItems: 'stretch', height: this.state.height, ...props.containerStyle}}>
                <TouchableWithoutFeedback onPress={props.onPress}>
                    <View style={{position: 'absolute', top: 0, left: 0, right: 0, bottom: 0}}/>
                </TouchableWithoutFeedback>
                <AutoHeightWebView
                    source={{html: html, baseUrl: ''}}
                    zoomable={false}
                    scrollEnabled={false}
                    useWebKit
                    renderToHardwareTextureAndroid={this.state.hardware}
                    androidHardwareAccelerationDisabled={true}
                    onMessage={(event) => {
                        const data = event.nativeEvent.data;
                        if (typeof (data) === 'string' && data.indexOf('{') !== 0) {
                            if (data.indexOf('^^^') > 0){
                                const s = data.split('^^^');
                                const images = s[0].split(',');
                                const image = s[1];
                                const index = images.indexOf(image);
                                if (props.onPressImage) {
                                    props.onPressImage(images, image, index);
                                }
                            }
                            else {
                                props.onMessage && props.onMessage(data);
                            }
                            event.nativeEvent = null;
                        }
                    }}
                    customScript={`
          var imgs = document.getElementsByTagName('img'); 
          var as = document.getElementsByTagName('a');
          
          ${this.props.filterScheme ? "for (var i = 0; i < as.length; ++i) { \
            var a = as[i]; \
            var href = a.href; \
            a.removeAttribute('href'); \
            a.setAttribute('cdy_href', href); \
            a.style.color='#315efb'; \
            a.style.textDecoration='underline'; \
            a.onclick=function(v){ \
                console.log(v);\
                window.ReactNativeWebView.postMessage(v.target.getAttribute('cdy_href')); \
            } \
          }" : ""}
           
          for (var i = 0; i < imgs.length; ++i) {
            var img = imgs[i];
            img.onclick=function(v){
            var imgs = document.getElementsByTagName('img');
            var srcs = [];
             for (var i = 0; i < imgs.length; ++i) {
              var img = imgs[i];
              ${this.props.onLargeImageCanPress ? 'if(img.width >= window.width)' : ''}
                {srcs.push(img.src)}
             }
            ${this.props.onLargeImageCanPress ? 'if(window.width == v.target.width)':''}
            {
              window.ReactNativeWebView.postMessage(srcs.toString() + "^^^" + v.target.src);
              }
            }
          }`}
                    style={props.htmlStyle}
                    overScrollMode={'never'}
                    customStyle={props.css}
                    onSizeUpdated={size => {

                        if (Math.abs(size.height - this.state.height) > 10 && size.height > 0) {
                            this.setState({height: size.height + 9});
                        }
                        props.onSizeUpdated && props.onSizeUpdated(size);
                        
                    }}
                />
            </View> : <View style={{
                justifyContent: "center",
                alignItems: "center",
                flexDirection: "row",
                flex: 1,
                backgroundColor:'white',
                width:'100%'
            }}>
                <ActivityIndicator size={"large"}/>
            </View>;
        }
    }
}

HTMLDisplayView.propTypes = {
    html: PropTypes.string,
    css: PropTypes.string,
    onSizeUpdated: PropTypes.func,
    onMessage: PropTypes.func,
    onPress: PropTypes.func,
    filterScheme: PropTypes.bool,
    containerStyle: PropTypes.object,
    textStyle: PropTypes.object,
    htmlStyle: PropTypes.object,
    onPressImage: PropTypes.func,
    onLargeImageCanPress: PropTypes.bool,
    autoResizingImage: PropTypes.bool
};

HTMLDisplayView.defaultProps = {
    autoResizingImage: true,
    onLargeImageCanPress: true,
    filterScheme: false
};
export default HTMLDisplayView;
